/**
 * 
 */
package be.redo.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import be.redo.model.entities.Customer;
import be.redo.model.entities.Employee;
import be.redo.model.entities.Vacation;

/**
 * @author Frank
 * 
 */
@Repository
public class VacationDAOImpl implements VacationDAO {
	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * @see be.redo.dao.VacationDAO#create(be.redo.model.entities.Vacation)
	 */
	@Override
	public void create(Vacation instance) {
		try {
			entityManager.persist(instance);
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.VacationDAO#read(long)
	 */
	@Override
	public Vacation read(long id) {
		return entityManager.find(Vacation.class, id);
	}

	/**
	 * @see be.redo.dao.VacationDAO#update(be.redo.model.entities.Vacation)
	 */
	@Override
	public void update(Vacation instance) {
		try {
			entityManager.merge(instance);
			entityManager.flush();
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.VacationDAO#delete(long)
	 */
	@Override
	public void delete(long id) {
		Vacation instance = entityManager.find(Vacation.class, id);
		if (instance != null) {
			entityManager.remove(instance);
			entityManager.flush();
		}
	}

	/**
	 * @see be.redo.dao.VacationDAO#findAll()
	 */
	@Override
	public List<Vacation> findAll() {
		TypedQuery<Vacation> query = entityManager.createNamedQuery(
				"findAllVacations", Vacation.class);
		return query.getResultList();
	}

	/**
	 * @see be.redo.dao.VacationDAO#count()
	 */
	@Override
	public int count() {
		TypedQuery<Number> query = entityManager.createNamedQuery(
				"findAantalVacations", Number.class);
		return (query.getSingleResult()).intValue();
	}

	/**
	 * @see be.redo.finders.VacationFinders#findVacationsByCustomer(be.redo.model.entities.Customer)
	 */
	@Override
	public List<Vacation> findVacationsByCustomer(Customer customer) {
		TypedQuery<Vacation> query = entityManager.createNamedQuery(
				"findVacationsByCustomere", Vacation.class);
		query.setParameter("customer", customer);
		return query.getResultList();
	}

	/**
	 * @see be.redo.finders.VacationFinders#findVacationsByRegistrationEmployee(be.redo.model.entities.Employee)
	 */
	@Override
	public List<Vacation> findVacationsByRegistrationEmployee(Employee employee) {
		TypedQuery<Vacation> query = entityManager.createNamedQuery(
				"findVacationsByRegistrationEmployee", Vacation.class);
		query.setParameter("employee", employee);
		return query.getResultList();
	}
}
